<?php
namespace Pay\Model;
use Think\Model;
/**
 * 支付状态表的Model
 * @author rockskyawp
 */
class PayStatusModel extends Model {
	
	/**
	 * 发起支付时插入支付状态表
	 * @param array $data
	 * @return boolean
	 */
	public function createStatus($data = array()){
		$result = FALSE;
		
		if (isset($data['order_no']) && isset($data['amount'])) {
			$status = $this -> where(array('order_no' => $data['order_no'])) -> find();
			if (!empty($status)) {
				$result = $status['status_id'];
			} else {
				$init_data = array(
					'order_no' => $data['order_no'],
					'order_title' => $data['order_title'] ? $data['order_title'] : '',
					'order_desc' => $data['order_desc'] ? $data['order_desc'] : '',
					'order_url' => $data['order_url'] ? $data['order_url'] : '',
					'amount' => $data['amount'],
				);
				
				if ($this -> validate() -> create($init_data)) {
					$result = $this -> add();
				}
			}
		}
		
		return $result;
	}
	
	/**
	 * 支付成功后更新支付状态表的状态
	 * @param array $data
	 * @return boolean
	 */
	public function updateStatus($data = array()) {
		$result = FALSE;
		
		if (isset($data['order_no']) && isset($data['amount']) && isset($data['status']) && isset($data['trade_no'])) {
			$status = $this -> where(array('order_no' => $data['order_no'])) -> find();
			if (empty($status)) {
				$result = FALSE;
			} elseif (!$status['status']) {
				if ($status['amount'] == $data['amount']) {
					$update_data['status'] = $data['status'];
					$update_data['trade_no'] = $data['trade_no'];
					$data['payfrom'] && $update_data['payfrom'] = $data['payfrom'];
					$data['data'] && $update_data['data'] = json_encode($data['data']);
					$data['time'] && $update_data['time'] = $data['time'];
						
					$result = $this -> where(array('order_no' => $data['order_no'])) -> save($update_data);
				} else {
					//实际支付金额与订单需要支付的金额不符,可能是非法修改或其它问题导致,此处应该做异常支付日志
					//TODO 异常支付日志
					$result = FALSE;
				}
			} else {
				$result = TRUE;
			}
		}
		
		return $result;
	}
	
}
